<?php

/**
 * A class for loading armory profiles
 * either from the official site or 
 * from a local XML file.
 * 
 * This unfortunately requires curl 
 * to work...
 */
class ArmoryProfile
{
	protected $_defaultServer = "http://eu.wowarmory.com";
	protected $_defaultRealm = "Dragonmaw";
	
	// Some values for interfacing with the armory
	protected $_timeout = 30; // Timeout for armory request
	protected $_useragent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1";
	
	/**
	 * Loads a armory profile from the official armory sites
	 *
	 * @param string $charname Character name
	 * @param string    $realm Realm name
	 * @param string   $server Server URL
	 */
	public function pull($charname,$realm=null,$server=null)
	{
		// Make sure that the character name is infact a valid name
		//if (!(is_string($charname) && preg_match("[A-Za-z0-9]+", $charname))) return;
		if ($realm==null) $realm = $this->_defaultRealm;
		if ($server==null) $server = $this->_defaultServer;
		
		$url = $server."/character-sheet.xml?r=".$realm."&n=".$charname;
		
		echo "Request: " . $url . "<br>";
		
		$response = ArmoryProfile::performArmoryRequest($url);
		
		/*
		// Perform the request using curl
		$curl = curl_init();
		curl_setopt ($curl, CURLOPT_URL, $url);
		curl_setopt ($curl, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt ($curl, CURLOPT_CONNECTTIMEOUT, $this->_timeout);
		curl_setopt ($curl, CURLOPT_USERAGENT, $this->_useragent);
		$contents = curl_exec($curl);
		curl_close($curl);
		*/
		
		$client = new Zend_Http_Client($url);
		$client->setConfig(array('useragent'=>$this->_useragent, 'timeout'=>$this->_timeout));
		
		$response = $client->request();

		$this->process($response->getBody());
	}
	
	/**
	 * Loads a local version of a armory profile
	 *
	 * @param string $xmlfile File location
	 */
	public function load($xmlfile)
	{
		
	}
	
	/**
	 * Utility function for processing the xml 
	 * returned from the armory or from a local
	 * file.
	 *
	 * @param string $xml
	 */
	protected function process($str)
	{
		$xml = simplexml_load_string($str);
		
		echo "<b>Items:</b> <br>";
		foreach($xml->characterInfo->characterTab->items->item as $item) {
			echo " &nbsp; Slot:".$item['slot']." id: ".$item['id']."<br>";
		}
	}
	
	protected static function performArmoryRequest($url)
	{
		$client = new Zend_Http_Client($url);
		$client->setConfig(array('useragent'=>$this->_useragent, 'timeout'=>$this->_timeout));
		$response = $client->request();
		
		if ($response->isSuccessful()) return $response->getBody();
		else return null;
	}
	
	public function setDefaultRealm($realm)
	{
		$this->_defaultRealm = $realm;
	}
	
	public function setDefaultServer($server)
	{
		$this->_defaultServer = $server;
	}
}